<?php

require_once 'Pipes/Exception.php';
require_once 'Pipes/FileSystem/Generic/Finder.php';
require_once 'PipesImpl/Visitor.php';

class Pipes_Model_Visitors_ExternalRelationshipSavers implements PipesImpl_Visitor
{
	private $_config = null;
	private $_finder = null;

	public function __construct(PipesImpl_Config $config) {
		$this->_config = $config;
		$this->_finder = new Pipes_FileSystem_Generic_Finder($config);
	}

	public function visit(PipesImpl_Visitable $visitable) {
		if (!$visitable instanceof PipesImpl_Model) {
			throw new Pipes_Exception('Invalid visitor: does not implement PipesImpl_Model');
		}
		$model = $visitable;

		$finder = new Pipes_FileSystem_File_Finder();
		$prefix = ucfirst($model->getName()) . '_';
		$file = false;
		foreach ($model->listRelationships() as $rel) {
			$relatedModel = ucfirst(substr($rel, 0, -1));
			try {
				$file = $this->_finder->find($prefix . 'Saver');
			} catch (Pipes_Exception $e) {
				// if a specific one does not exist, try the generic RelationshipSaver
				try {
					$file = $this->_finder->find('Models_Savers_' . $relatedModel . 'RelationshipSaver');
				} catch (Pipes_Exception $e) {
					// we can't deal with this, let save continue to do its thing
					$file = false;
				}
			}

			if ($file !== false) {
				$file->requireOnce();
				$saver = $this->_finder->lastLoaded;
				$saverObj = new $saver($this->_config, $model);
				$saverObj->save();
			}
		}
	}
}
